package org.baicaixiaozhan.learncommon.util.accesslimit;

import lombok.SneakyThrows;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.baicaixiaozhan.learncommon.util.annotation.AccessLimit;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

/**
 * DESC:
 *
 * @since 2021-07-01
 * @author baicaixiaozhan
 */
@Component
@Aspect
public class AccessLimitAspect {


    @Pointcut("@annotation(org.baicaixiaozhan.learncommon.util.annotation.AccessLimit)")
    public void pointcut() {}

    @SneakyThrows
    @Before("pointcut() && @annotation(accessLimit)")
    public void beforeAccess(AccessLimit accessLimit) {
        Class<?> value = accessLimit.value();
        Object obj = value.getDeclaredConstructor().newInstance();
        if (obj instanceof AccessLimiter) {
            if (accessLimit.count() > 0L && accessLimit.timeOfMinutes() > 0L) {
                ReflectionUtils.invokeMethod(value.getDeclaredMethod("startAccessLimit", long.class, long.class), obj,
                        accessLimit.count(), accessLimit.timeOfMinutes());
            } else {
                ReflectionUtils.invokeMethod(value.getDeclaredMethod("startAccessLimit"), obj);
            }
        }
    }

}
